﻿
using System;
using System.Collections.Generic;
using System.Text;

namespace SharpSoft.Web
{
    using Microsoft.AspNetCore.Mvc;
    using System.Net.WebSockets;
    using System.Threading.Tasks;
    /// <summary>
    /// WebSocket消息服务
    /// </summary>
    public class wsmsgserController : Controller
    {
        wsMsgService service;
        public wsmsgserController(wsMsgService p_service)
        {
            service = p_service;
        }
        /// <summary>
        /// 发起websocket连接(在websocket连接关闭时Action不应立即返回)
        /// </summary>
        /// <param name="key">为websocket的消息指定一个键</param>
        /// <returns></returns>
        [Route("/ws")]
        [HttpGet]
        public async Task Ws(string key = null)
        {
            if (key == null)
            {
                key = Guid.NewGuid().ToString();
            }
            if (HttpContext.WebSockets.IsWebSocketRequest)
            {
                var wc = await HttpContext.WebSockets.AcceptWebSocketAsync();
                await service.ClientAccepted(wc, key.ToLower());
            }
        }
    }
}
